package com.niiwoo.civet.account.service.local.check.job.apiservice.allbalance;

import com.dangdang.ddframe.rdb.sharding.api.HintManager;
import com.dangdang.ddframe.rdb.sharding.hint.HintManagerHolder;
import com.github.pagehelper.PageHelper;
import com.niiwoo.civet.account.dao.entity.AccountBase;
import com.niiwoo.civet.account.dao.entity.AccountBaseExample;
import com.niiwoo.civet.account.dao.entity.AccountCheckingAllbalance;
import com.niiwoo.civet.account.dao.entity.AccountCheckingException;
import com.niiwoo.civet.account.dao.mapper.AccountBaseMapperExt;
import com.niiwoo.civet.account.dao.mapper.AccountCheckingAccountStatisticsMapperExt;
import com.niiwoo.civet.account.dao.mapper.AccountCheckingAllbalanceMapperExt;
import com.niiwoo.civet.account.dto.request.AccountCheckingAllbalanceRequestDTO;
import com.niiwoo.civet.account.initialize.Singleton;
import com.niiwoo.civet.account.service.local.check.job.api.CheckDetailService;
import com.niiwoo.civet.account.service.local.check.job.api.ParseService;
import com.niiwoo.civet.account.service.local.check.job.util.DateUtil;
import com.niiwoo.civet.base.constant.OrgConstant;
import com.niiwoo.tripod.lanmao.enums.PlateformAccountEnum;
import com.niiwoo.tripod.lanmao.enums.UserRoleEnum;
import com.niiwoo.tripod.lanmao.properties.LanMaoProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class AllbalanceCheckDetailServiceImpl implements CheckDetailService<AccountCheckingAllbalance>,ParseService<AccountCheckingAllbalance> {

   @Autowired
   private AccountCheckingAllbalanceMapperExt accountCheckingAllbalanceMapperExt;
   @Autowired
   private AccountCheckingAccountStatisticsMapperExt accountCheckingAccountStatisticsMapperExt;
   @Autowired
   private LanMaoProperties lanMaoProperties;
   @Autowired
   private AccountBaseMapperExt accountBaseMapperExt;

    @Override
    public List<AccountCheckingAllbalance> load(Long checkRecordId, int page, int pageSize) {
    	// shardingjdbc 强制走主库
		if (!HintManagerHolder.isMasterRouteOnly()) {
            HintManagerHolder.clear();
            HintManager hintManager = HintManager.getInstance();
            hintManager.setMasterRouteOnly();
        }
		log.debug("is matster route only : {}", HintManagerHolder.isMasterRouteOnly());
        AccountCheckingAllbalanceRequestDTO accountCheckingAllbalanceRequestDTO = new AccountCheckingAllbalanceRequestDTO();
        PageHelper.startPage(page, pageSize,false);
        accountCheckingAllbalanceRequestDTO.setCheckingRecordId(checkRecordId);
        accountCheckingAllbalanceRequestDTO.setStatus(Byte.valueOf("1"));
        List<AccountCheckingAllbalance> accountCheckingAllbalanceList = (List<AccountCheckingAllbalance>) accountCheckingAllbalanceMapperExt.queryCheckingAllBalancePage(accountCheckingAllbalanceRequestDTO);
        return accountCheckingAllbalanceList;
    }

    @Override
    public void batchUpdateCheckDetailStatus(Long checkRecordId, Byte status) {
        accountCheckingAllbalanceMapperExt.updateStatusByCheckingRecordId(checkRecordId,status);
    }

    @Override
    public AccountCheckingException check(AccountCheckingAllbalance accountCheckingAllbalance, String checkDate) {
        return null;
    }

    @Override
    public AccountCheckingAllbalance parse(Long recordId, String content) {
        if (content == null || "".equals(content))
            return null;

        String[] sArr = content.split(",");

        /*AccountCheckingAllbalance record = new AccountCheckingAllbalance();
        //0:汇总时间,1:平台编号,2:会员编号,3:平台会员编号,4:币种,5:账户总余额
        record.setCollectTime(DateUtil.parseCheckDate(sArr[0]));
        record.setPlatformMerchantNo(sArr[1]);
        record.setMemberNo(sArr[2]);
        record.setPlatformUserNo(sArr[3]);
        record.setAmonnt("人民币"); //4-人民币
        record.setAmount(BigDecimal.valueOf(Double.valueOf(sArr[5])));

        record.setStatus((byte) 1); // 1待处理
        record.setCheckingRecordId(recordId);
        return record;*/

        // 老版
        //期末余额：平台总账户、平台收入账户、平台营销款账户、担保公司账户；
        String guaranteeUserId = lanMaoProperties.getNiiWooAccount().getGuaranteeUserId();
        Set<String> platformAccountSet = new HashSet<>();
        platformAccountSet.add(PlateformAccountEnum.SYS_GENERATE_000.toString());
        platformAccountSet.add(PlateformAccountEnum.SYS_GENERATE_002.toString());
        platformAccountSet.add(PlateformAccountEnum.SYS_GENERATE_003.toString());
        platformAccountSet.add(PlateformAccountEnum.SYS_GENERATE_004.toString());
        platformAccountSet.add(guaranteeUserId);
        if(null != Singleton.getInstance().getOrgNiWoTa()){
            String orgNiWoTaAccountNO = Singleton.getInstance().getOrgNiWoTa().getAccountNO();
            platformAccountSet.add(orgNiWoTaAccountNO);//166685907595796480
        }

        if(platformAccountSet.contains(sArr[3])) {
            return arraysToObject(sArr,recordId);
        }else{
            AccountBaseExample accountBaseExample = new AccountBaseExample();
            AccountBaseExample.Criteria accountBaseCriteria = accountBaseExample.createCriteria();
            accountBaseCriteria.andAccountRoleEqualTo(UserRoleEnum.GUARANTEECORP.getValue());
            accountBaseCriteria.andAccountNoEqualTo(sArr[3]);
            List<AccountBase> accountBaseList = accountBaseMapperExt.selectByExample(accountBaseExample);
            if( null != accountBaseList && accountBaseList.size() > 0 ){
                return arraysToObject(sArr,recordId);
            }
        }
        return null;
    }

    private AccountCheckingAllbalance arraysToObject(String [] sArr,long recordId){
        AccountCheckingAllbalance record = new AccountCheckingAllbalance();
        //0:汇总时间,1:平台编号,2:会员编号,3:平台会员编号,4:币种,5:账户总余额
        record.setCollectTime(DateUtil.parseCheckDate(sArr[0]));
        record.setPlatformMerchantNo(sArr[1]);
        record.setMemberNo(sArr[2]);
        record.setPlatformUserNo(sArr[3]);
        record.setAmonnt("人民币"); //4-人民币
        record.setAmount(BigDecimal.valueOf(Double.valueOf(sArr[5])));

        record.setStatus((byte) 1); // 1待处理
        record.setCheckingRecordId(recordId);
        return record;
    }

    @Override
    public void save(List<AccountCheckingAllbalance> list) {
        if (list == null || list.isEmpty())
            return;
        //accountCheckingWithdrawMapperExt.insertBatch(list);
        for(AccountCheckingAllbalance accountCheckingAllbalance : list){
            accountCheckingAllbalanceMapperExt.insert(accountCheckingAllbalance);
        }
    }

    @Override
    public void deleteCheckRecord(Long recordId) {
        accountCheckingAllbalanceMapperExt.deleteByCheckingRecordId(recordId);
    } 

    @Override
    public void extendBusiness(Long checkRecordId) {
        //totalAllBalance(checkRecordId);
    }

	@Override
	public void deleteAllCheckSuccessBankOrder(Long checkRecordId) {
        accountCheckingAllbalanceMapperExt.deleteByCheckingRecordId(checkRecordId);
	}
}
